/*
 * Copyright 2013 HVTTGROUP
 * Tool Genneric code by HVTTGROUP
 * @version v1.0
 * @see http://hvttgroup.com
 *
 */
package com.hvtt.web.controller;

import com.hvtt.web.controllerUtils.MainController;
import com.hvtt.web.controllerUtils.UtilsController;
import com.hvtt.web.models.User;
import com.hvtt.web.models.datatable.DefaultLazyDataModel;
import com.hvtt.web.utilities.ConstClass;
import com.hvtt.web.utilities.Utilities;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.el.MethodExpression;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.event.MethodExpressionActionListener;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.component.commandbutton.CommandButton;
import org.primefaces.component.datatable.DataTable;
import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.data.FilterEvent;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.UploadedFile;

/**
 *
 * @author Nguyen Hoang Danh
 */
@ManagedBean
@SessionScoped
public class UserController implements Serializable{
    // <editor-fold defaultstate="collapsed" desc="Properties class"> 

    private User user;
    private User currentUser;
    private User oldUser;
    public static final String SCREEN_CODE = "User";
    private LazyDataModel<User> userLazy;
    private List<User> lstSelected;
    private final static String FOLDER_NAME = "User";
    private final static String COMPONENT_TABLE_ID = "userTB";
    private UploadedFile uploadedFile;
    private boolean reloadable = false;

    // </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="Constructor class"> 
    public UserController() {
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Private Method Code">  

    private String validateFields(User user1) throws SQLException {
        if (StringUtils.isBlank(user1.getUserID())
                || StringUtils.isBlank(user1.getPassword())
                || StringUtils.isBlank(user1.getFullName())) {
            return Utilities.getLanguages("AdMsg0010");
        }
        return "";
    }

    public String getViewId() {
        String viewId = FacesContext.getCurrentInstance().getViewRoot().getViewId();
        String selectedMenu;
        if (viewId != null) {
            selectedMenu = viewId.substring(viewId.lastIndexOf("/") + 1, viewId.lastIndexOf("."));
        } else {
            selectedMenu = null;
        }

        return selectedMenu;
    }

    // </editor-fold> 
    // <editor-fold defaultstate="collapsed" desc="Public method">

/**
     * Initialize data when class created
     */
    public void initialize() {
        userLazy = new DefaultLazyDataModel(this.getUser().findAll(), User.filterFields());
        setReloadable(false);
    }
    public void loadDataTable() {
        if (userLazy == null) {
            this.initialize();
        } else {
            List<User> lst = (List<User>) this.getUserLazy().getWrappedData();
            if (!lst.isEmpty()) {
                lst.clear();
            }
            if (lstSelected != null) {
                lstSelected.clear();
            }
            lst.addAll(this.getUser().findAll());
            setReloadable(false);
        }
    }

    public void bindingData(ComponentSystemEvent event) {
        if (isReloadable() || !FacesContext.getCurrentInstance().isPostback()) {
            loadDataTable();
        }
    }

    // </editor-fold> 
    // <editor-fold defaultstate="collapsed" desc="Event Listener code for keys event ( two pane view )">
    /**
     * Show all modules for find edit more
     *
     * @param event
     */
    public void eventKeyF3(ActionEvent event) {
        this.setReloadable(true);
        RequestContext.getCurrentInstance().execute("PF('wDlgModules').show();");
    }

    /**
     * save method for key event
     *
     * @param event
     */
    public void keyEventSave(ActionEvent event) throws SQLException {
        String result = this.validateFields(this.getUser());
        if (!result.isEmpty()) {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status", result);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            RequestContext.getCurrentInstance().execute("validateForm('newUser_required','valiRequired');");
            return;
        }

        boolean b = this.getUser().save();
        if (b) {
            this.getOldUser().newInstance(this.getUser());
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Message Status", Utilities.getLanguages("AdMsg0002"));
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } else {
            int codeError = this.getUser().getWebConnection().getCodeError();
            UtilsController utilsController = Utilities.getManagedBean(UtilsController.class);
            if (codeError == 1062) {
                utilsController.setMessage(Utilities.getLanguages("AdMsg0003"));
                utilsController.setMsgImage("/Administrator/images/alert.png");
                CommandButton commandButton = (CommandButton) FacesContext.getCurrentInstance().getViewRoot().findComponent("bntEventOK");
                FacesContext context = FacesContext.getCurrentInstance();
                MethodExpression actionListener = context.getApplication().getExpressionFactory()
                        .createMethodExpression(context.getELContext(), "#{userController.echoKeyEventUpdate}", null, new Class[]{ActionEvent.class});
                ActionListener[] actionListeners = commandButton.getActionListeners();
                if (actionListeners != null && actionListeners.length > 0) {
                    commandButton.removeActionListener(actionListeners[0]);
                }
                commandButton.addActionListener(new MethodExpressionActionListener(actionListener));
                commandButton.setUpdate(ConstClass.UIID.COMPONENT_ROOT_FORM_ID + ":messages");
                RequestContext.getCurrentInstance().execute("PF('msg0002').show()");
            } else {
                utilsController.setMessage(Utilities.getMessageErrorFromCode(codeError));
                RequestContext.getCurrentInstance().execute("PF('msg0001').show()");
            }
        }
    }

    public void echoKeyEventUpdate(ActionEvent event) throws SQLException {
        boolean b = this.getUser().update();
        if (b) {
            this.getOldUser().newInstance(this.getUser());
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Message Status", Utilities.getLanguages("AdMsg0002"));
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } else {
            UtilsController utilsController = Utilities.getManagedBean(UtilsController.class);
            utilsController.setMessage(this.getUser().getWebConnection().getMessageError());
            utilsController.setMsgImage("/Administrator/images/warning.png");
            RequestContext.getCurrentInstance().execute("PF('msg0001').show()");
        }
    }

    public void keyEvent(ActionEvent event) {
        FacesContext fc = FacesContext.getCurrentInstance();
        Map map2 = fc.getExternalContext().getRequestParameterMap();
        String newCodes = (String) map2.get("code");
        System.out.println("New codes ::" + newCodes);
    }

    public void keyEvent1(ActionEvent event) {
        RequestContext.getCurrentInstance().execute("PF('wDlgModules').show();");
    }

// </editor-fold> 
    // <editor-fold defaultstate="collapsed" desc="Event Listener code ( two pane view )"> 
    public void create(ActionEvent event) {
        if (this.getUser() != null) {
            this.getUser().resetAttribute();
        }
        if (this.getOldUser() != null) {
            this.getOldUser().resetAttribute();
        }
        MainController controller = Utilities.getManagedBean(MainController.class);
        controller.setIncludePage("ui/new/newUser.xhtml");
    }

    public void refresh(ActionEvent event) {
        this.setReloadable(true);
        Utilities.fixSizeContent(COMPONENT_TABLE_ID);
    }

    public void delete(ActionEvent event) throws SQLException {
        if (!lstSelected.isEmpty()) {
            UtilsController utilsController = Utilities.getManagedBean(UtilsController.class);
            utilsController.setMessage(Utilities.getLanguages("AdMsg0001"));
            utilsController.setMsgImage("/Administrator/images/alert.png");
            CommandButton commandButton = (CommandButton) FacesContext.getCurrentInstance().getViewRoot().findComponent("bntEventOK");
            FacesContext context = FacesContext.getCurrentInstance();
            MethodExpression actionListener = context.getApplication().getExpressionFactory()
                    .createMethodExpression(context.getELContext(), "#{userController.echoDelete}", null, new Class[]{ActionEvent.class});
            ActionListener[] actionListeners = commandButton.getActionListeners();
            if (actionListeners != null && actionListeners.length > 0) {
                commandButton.removeActionListener(actionListeners[0]);
            }
            commandButton.addActionListener(new MethodExpressionActionListener(actionListener));
            RequestContext.getCurrentInstance().execute("PF('msg0002').show()");
        }
    }

    public void echoDelete(ActionEvent event) {
        ((List<User>) this.getUserLazy().getWrappedData()).removeAll(lstSelected);
        boolean b = this.getUser().remove(lstSelected);
        if (!b) {
            UtilsController utilsController = Utilities.getManagedBean(UtilsController.class);
            utilsController.setMessage(Utilities.getMessageErrorFromCode(this.getUser().getWebConnection().getCodeError()));
            utilsController.setMsgImage("/Administrator/images/warning.png");
            RequestContext.getCurrentInstance().execute("PF('msg0001').show()");
        }
        this.setReloadable(true);
        Utilities.fixSizeContent(COMPONENT_TABLE_ID);
        RequestContext.getCurrentInstance().update(ConstClass.UIID.COMPONENT_ROOT_FORM_ID+":"+COMPONENT_TABLE_ID);
    }

    public void rowDbClickEdit(SelectEvent ev) {
        if (!lstSelected.isEmpty()) {
            MainController mainController = Utilities.getManagedBean(MainController.class);
            mainController.setIncludePage("ui/new/newUser.xhtml");
            User bObject = lstSelected.get(0);
            this.getUser().newInstance(bObject);
            this.getOldUser().newInstance(bObject);
        }
    }

    public void filter(FilterEvent event) {
    }

// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="Event Listener Code For Context menu ( tưo pane view )"> 
    public void ctxView(ActionEvent event) throws SQLException {
        UtilsController utilsController = Utilities.getManagedBean(UtilsController.class);
        utilsController.unsupportMethod();
    }

    public void ctxCreate(ActionEvent event) {
        if (this.getUser() != null) {
            this.getUser().resetAttribute();
        }
        if (this.getOldUser() != null) {
            this.getOldUser().resetAttribute();
        }
        MainController controller = Utilities.getManagedBean(MainController.class);
        controller.setIncludePage("ui/new/newUser.xhtml");
    }

    public void ctxRefresh(ActionEvent event) {
        this.setReloadable(true);
        Utilities.fixSizeContent(COMPONENT_TABLE_ID);
    }

    public void ctxSelectAll(ActionEvent event) {
        DataTable dataTable = (DataTable) FacesContext.getCurrentInstance().getViewRoot()
                .findComponent(ConstClass.UIID.COMPONENT_ROOT_FORM_ID + ":" + COMPONENT_TABLE_ID);
        int rowCount = dataTable.getRowCount();
        int first = dataTable.getFirst();
        int rowDisplay = dataTable.getRows();
        int limit = first + rowDisplay;
        List<User> lstData = (List<User>) this.getUserLazy().getWrappedData();
        List<User> lstSelect;
        if (limit > rowCount) {
            lstSelect = lstData.subList(first, rowCount);
        } else {
            lstSelect = lstData.subList(first, limit);
        }
        lstSelected.clear();
        lstSelected.addAll(lstSelect);

        Utilities.fixSizeContent(COMPONENT_TABLE_ID);
    }

    public void ctxEdit(ActionEvent event) {
        if (!lstSelected.isEmpty()) {
            MainController mainController = Utilities.getManagedBean(MainController.class);
            mainController.setIncludePage("ui/new/newUser.xhtml");
            User objUser = lstSelected.get(0);
            this.getUser().newInstance(objUser);
            this.getOldUser().newInstance(objUser);
        }
    }

    public void ctxDelete(ActionEvent event) throws SQLException {
        if (!lstSelected.isEmpty()) {
            UtilsController utilsController = Utilities.getManagedBean(UtilsController.class);
            utilsController.setMessage(Utilities.getLanguages("AdMsg0001"));
            utilsController.setMsgImage("/Administrator/images/alert.png");
            CommandButton commandButton = (CommandButton) FacesContext.getCurrentInstance().getViewRoot().findComponent("bntEventOK");
            FacesContext context = FacesContext.getCurrentInstance();
            MethodExpression actionListener = context.getApplication().getExpressionFactory()
                    .createMethodExpression(context.getELContext(), "#{userController.ctxEchoDelete}", null, new Class[]{ActionEvent.class});
            ActionListener[] actionListeners = commandButton.getActionListeners();
            if (actionListeners != null && actionListeners.length > 0) {
                commandButton.removeActionListener(actionListeners[0]);
            }
            commandButton.addActionListener(new MethodExpressionActionListener(actionListener));
            RequestContext.getCurrentInstance().execute("PF('msg0002').show()");
        }
    }

    public void ctxEchoDelete(ActionEvent event) {
        ((List<User>) this.getUserLazy().getWrappedData()).removeAll(lstSelected);
        boolean b = this.getUser().remove(lstSelected);
        if (!b) {
            UtilsController utilsController = Utilities.getManagedBean(UtilsController.class);
            utilsController.setMessage(Utilities.getMessageErrorFromCode(this.getUser().getWebConnection().getCodeError()));
            utilsController.setMsgImage("/Administrator/images/warning.png");
            RequestContext.getCurrentInstance().execute("PF('msg0001').show()");
        }
        this.setReloadable(true);
        Utilities.fixSizeContent(COMPONENT_TABLE_ID);
        RequestContext.getCurrentInstance().update(ConstClass.UIID.COMPONENT_ROOT_FORM_ID+":"+COMPONENT_TABLE_ID);
    }

    public void ctxDeleteAll(ActionEvent event) throws SQLException {
        UtilsController utilsController = Utilities.getManagedBean(UtilsController.class);
        utilsController.setMessage(Utilities.getLanguages("AdMsg0001"));
        utilsController.setMsgImage("/Administrator/images/alert.png");
        CommandButton commandButton = (CommandButton) FacesContext.getCurrentInstance().getViewRoot().findComponent("bntEventOK");
        FacesContext context = FacesContext.getCurrentInstance();
        MethodExpression actionListener = context.getApplication().getExpressionFactory()
                .createMethodExpression(context.getELContext(), "#{userController.ctxEchoDeleteAll}", null, new Class[]{ActionEvent.class});
        ActionListener[] actionListeners = commandButton.getActionListeners();
        if (actionListeners != null && actionListeners.length > 0) {
            commandButton.removeActionListener(actionListeners[0]);
        }
        commandButton.addActionListener(new MethodExpressionActionListener(actionListener));
        RequestContext.getCurrentInstance().execute("PF('msg0002').show()");
    }

    public void ctxEchoDeleteAll(ActionEvent event) {
        DataTable dataTable = (DataTable) FacesContext.getCurrentInstance()
                .getViewRoot().findComponent(ConstClass.UIID.COMPONENT_ROOT_FORM_ID + ":" + COMPONENT_TABLE_ID);
        int rowCount = dataTable.getRowCount();
        int first = dataTable.getFirst();
        int rowDisplay = dataTable.getRows();
        int limit = first + rowDisplay;
        List<User> lstData = (List<User>) this.getUserLazy().getWrappedData();
        List<User> lstRemove;
        if (limit > rowCount) {
            lstRemove = lstData.subList(first, rowCount);
        } else {
            lstRemove = lstData.subList(first, limit);
        }
        this.getUser().remove(lstRemove);
        lstData.removeAll(lstRemove);
        this.setReloadable(true);
        Utilities.fixSizeContent(COMPONENT_TABLE_ID);
        RequestContext.getCurrentInstance().update(ConstClass.UIID.COMPONENT_ROOT_FORM_ID+":"+COMPONENT_TABLE_ID);
    }

    public void ctxProperty(ActionEvent event) {
        Utilities.createDialog("View : Info", true,
                "viewPropertiesSy001", "formDialog", "/modules/system/ViewPage/properties.xhtml", "sy001Controller.closeDialog");
        RequestContext.getCurrentInstance().execute("viewPropertiesSy001.show();");
    }

// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="Event Listener for new page">
    public void save(ActionEvent event) throws SQLException {
        String result = this.validateFields(this.getUser());
        if (!result.isEmpty()) {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status", result);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            RequestContext.getCurrentInstance().execute("validateForm('newUser_required','valiRequired');");
            return;
        }
        boolean b = this.getUser().save();
        if (b) {

            this.getOldUser().newInstance(this.getUser());
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Message Status", Utilities.getLanguages("AdMsg0002"));
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } else {
            int codeError = this.getUser().getWebConnection().getCodeError();
            UtilsController utilsController = Utilities.getManagedBean(UtilsController.class);
            if (codeError == 1062) {
                utilsController.setMessage(Utilities.getLanguages("AdMsg0003"));
                utilsController.setMsgImage("/Administrator/images/alert.png");
                CommandButton commandButton = (CommandButton) FacesContext.getCurrentInstance().getViewRoot().findComponent("bntEventOK");
                FacesContext context = FacesContext.getCurrentInstance();
                MethodExpression actionListener = context.getApplication().getExpressionFactory()
                        .createMethodExpression(context.getELContext(), "#{userController.echoUpdate}", null, new Class[]{ActionEvent.class});
                ActionListener[] actionListeners = commandButton.getActionListeners();
                if (actionListeners != null && actionListeners.length > 0) {
                    commandButton.removeActionListener(actionListeners[0]);
                }
                commandButton.addActionListener(new MethodExpressionActionListener(actionListener));
                commandButton.setUpdate(ConstClass.UIID.COMPONENT_ROOT_FORM_ID + ":messages");
                RequestContext.getCurrentInstance().execute("PF('msg0002').show()");
            } else {
                utilsController.setMessage(Utilities.getMessageErrorFromCode(codeError));
                RequestContext.getCurrentInstance().execute("PF('msg0001').show()");
            }
        }
    }

    public void echoUpdate(ActionEvent event) throws SQLException {
        boolean b = this.getUser().update();
        if (b) {
            
            //update oldOldBasicDBObject
            this.getOldUser().newInstance(this.getUser());
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Message Status", Utilities.getLanguages("AdMsg0002"));
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } else {
            UtilsController utilsController = Utilities.getManagedBean(UtilsController.class);
            utilsController.setMessage(Utilities.getMessageErrorFromCode(this.getUser().getWebConnection().getCodeError()));
            utilsController.setMsgImage("/Administrator/images/warning.png");
            RequestContext.getCurrentInstance().execute("PF('msg0001').show()");
        }
    }
    public void saveCurrentUser(ActionEvent event) throws SQLException {
        String result = this.validateFields(this.getCurrentUser());
        if (!result.isEmpty()) {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status", result);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            RequestContext.getCurrentInstance().execute("validateForm('newUser_required','valiRequired');");
            return;
        }
//        this.getCurrentUser().setPassword(Utilities.encrypt(this.getCurrentUser().getPassword()));
        boolean b = this.getCurrentUser().save();
        if (b) {

            this.getOldUser().newInstance(this.getUser());
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Message Status", Utilities.getLanguages("AdMsg0002"));
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } else {
            int codeError = this.getCurrentUser().getWebConnection().getCodeError();
            UtilsController utilsController = Utilities.getManagedBean(UtilsController.class);
            if (codeError == 1062) {
                utilsController.setMessage(Utilities.getLanguages("AdMsg0003"));
                utilsController.setMsgImage("/Administrator/images/alert.png");
                CommandButton commandButton = (CommandButton) FacesContext.getCurrentInstance().getViewRoot().findComponent("bntEventOK");
                FacesContext context = FacesContext.getCurrentInstance();
                MethodExpression actionListener = context.getApplication().getExpressionFactory()
                        .createMethodExpression(context.getELContext(), "#{userController.echoUpdateCurrentUser}", null, new Class[]{ActionEvent.class});
                ActionListener[] actionListeners = commandButton.getActionListeners();
                if (actionListeners != null && actionListeners.length > 0) {
                    commandButton.removeActionListener(actionListeners[0]);
                }
                commandButton.addActionListener(new MethodExpressionActionListener(actionListener));
                commandButton.setUpdate(ConstClass.UIID.COMPONENT_ROOT_FORM_ID + ":messages");
                RequestContext.getCurrentInstance().execute("PF('msg0002').show()");
            } else {
                utilsController.setMessage(Utilities.getMessageErrorFromCode(codeError));
                RequestContext.getCurrentInstance().execute("PF('msg0001').show()");
            }
        }
    }
    public void echoUpdateCurrentUser(ActionEvent event) throws SQLException {
        boolean b = this.getCurrentUser().update();
        if (b) {
            
            //update oldOldBasicDBObject
            this.getOldUser().newInstance(this.getUser());
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Message Status", Utilities.getLanguages("AdMsg0002"));
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } else {
            UtilsController utilsController = Utilities.getManagedBean(UtilsController.class);
            utilsController.setMessage(Utilities.getMessageErrorFromCode(this.getUser().getWebConnection().getCodeError()));
            utilsController.setMsgImage("/Administrator/images/warning.png");
            RequestContext.getCurrentInstance().execute("PF('msg0001').show()");
        }
    }

    public void resetForm(ActionEvent event) {
        if (this.getOldUser() != null) {
            this.getUser().newInstance(this.getOldUser());
        } else {
            this.getUser().resetAttribute();
        }
    }

    public void cancelCreate(ActionEvent event) {
        if (this.getUser() != null) {
            this.getUser().resetAttribute();
        }
        if (this.getOldUser() != null) {
            this.getOldUser().resetAttribute();
        }
        MainController mainController = Utilities.getManagedBean(MainController.class);
        mainController.setIncludePage("ui/user.xhtml");
        this.setReloadable(true);
    }

    public void handleFileUpload(FileUploadEvent event) {
        UploadedFile file = event.getFile();
//        sy001.setIcon(Utilities.generateFileNameUpload(file.getFileName()));
//        this.setUploadedFile(file);
    }

    // </editor-fold>
    public boolean isReloadable() {
        return reloadable;
    }

    public void setReloadable(boolean reloadable) {
        this.reloadable = reloadable;
    }

    public LazyDataModel<User> getUserLazy() {
        return userLazy;
    }

    public void setUserLazy(LazyDataModel<User> userLazy) {
        this.userLazy = userLazy;
    }

    public User getUser() {
        if (user == null) {
            user = new User();
        }
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public void setOldUser(User oldUser) {
        this.oldUser = oldUser;
    }

    public User getOldUser() {
        if (oldUser == null) {
            oldUser = new User();
        }
        return oldUser;
    }

    public List<User> getLstSelected() {
        return lstSelected;
    }

    public void setLstSelected(List<User> lstSelected) {
        this.lstSelected = lstSelected;
    }
    
    // <editor-fold defaultstate="collapsed" desc="User define code"> 

    public void setCurrentUser(User currentUser) {
        this.currentUser = currentUser;
    }
    public void doProfile(ActionEvent event){
//        System.out.println(currentUser);
    }
    

    // </editor-fold>

    public User getCurrentUser() {
        return currentUser;
    }
}
